package com.example.multipledatasourcesdemo.controller;

import com.example.multipledatasourcesdemo.datasource.DynamicDataSourceContextHolder;
import com.example.multipledatasourcesdemo.model.Common;
import com.example.multipledatasourcesdemo.model.User;
import com.example.multipledatasourcesdemo.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Zenan Chen
 * @date 2023/4/14 17:26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @ApiOperation("查询default数据库用户")
    @PostMapping("/getDefaultUsers")
    private Object getUsers() {
        try {
            log.info("------------------------->/getDefaultUsers 查询default数据库用户开始");
            DynamicDataSourceContextHolder.setDataSourceType(Common.DS_DEFAULT);
            List<User> result = userService.getUsers();
            log.info("------------------------->/getDefaultUsers 查询default数据库用户结束");
            return result;
        } catch (Exception e) {
            log.error("------------------------->/getDefaultUsers 查询default数据库用户异常【{}】", e.getMessage());
            return "查询default数据库用户异常" + e.getMessage();
        }
    }

    @ApiOperation("查询ds1数据库用户")
    @PostMapping("/getDS1Users")
    private Object getDS1Users() {
        try {
            log.info("------------------------->/getDS1Users 查询ds1数据库用户开始");
            DynamicDataSourceContextHolder.setDataSourceType(Common.DS_DS1);
            List<User> result = userService.getUsers();
            log.info("------------------------->/getDS1Users 查询ds1数据库用户结束");
            return result;
        } catch (Exception e) {
            log.error("------------------------->/getDS1Users 查询ds1数据库用户异常【{}】", e.getMessage());
            return "查询ds1数据库用户异常" + e.getMessage();
        }
    }
}
